package pl.edu.agh.inpema.components.analyzers.simpleIPAnalyzer;

import java.util.List;

import org.apache.log4j.Logger;

import pl.edu.agh.inpema.components.analyzers.simpleIPAnalyzer.data.SingleIpCounter;
import pl.edu.agh.inpema.core.components.AnalyzerUtil;
import pl.edu.agh.inpema.core.model.Message;

public class SimpleIPAnalyzerRunner extends Thread {

	private boolean isRunning = false;
	private boolean queueEmpty = false;
	private boolean error = false;
	
	private static Logger logger = Logger.getLogger(SimpleIPAnalyzerRunner.class);
	
	private AnalyzerUtil analyzerUtil;
	
	public SimpleIPAnalyzerRunner() {
	}
	
	public void run() {
		isRunning = true;
		try {
			while (isRunning || !queueEmpty) {
				Message message = this.analyzerUtil.getNextMessage();
				
				if (message == null) {
					queueEmpty = true;
					continue;
				}
				queueEmpty = false;
				
				Integer resultId = this.analyzerUtil.getResultId(message.getProfileId());
				
				String ip = message.getField(Message.FIELD_IP);
				
				SingleIpCounter counter = null;
				List<Object> resultObjects = this.analyzerUtil.getResultObjects(resultId, SingleIpCounter.class);
				if (resultObjects == null || resultObjects.size() == 0) {
					counter = new SingleIpCounter();
					counter.setIp(ip);
					counter.setCounter(0);
					counter.setResultId(resultId);
				} else {
					for (Object obj : resultObjects) {
						SingleIpCounter c = (SingleIpCounter) obj;
						if (c.getIp().equals(ip)) {
							counter = c;
							break;
						}
					}
					if (counter == null) {
						counter = new SingleIpCounter();
						counter.setIp(ip);
						counter.setCounter(0);
						counter.setResultId(resultId);
					}
				}
				counter.setCounter(counter.getCounter() + 1);
				this.analyzerUtil.addResultObject(counter);
			}
		} catch (Exception e) {
			this.isRunning = false;
			this.error = true;
			e.printStackTrace();
		}
		//System.out.println("analyzer thread stop");
	}

	
	public void setRunningFalse() {
		isRunning = false;
	}
	
	public boolean isRunning() {
		return isRunning;
	}
	
	public boolean isError() {
		return this.error;
	}
	
	public void setAnalyzerUtil(AnalyzerUtil analyzerUtil) {
		this.analyzerUtil = analyzerUtil;
	}
}
